/*
 * @Description:
 * @Author: dh
 * @Date: 2022-01-21 13:41:19
 * @LastEditors: dh
 * @LastEditTime: 2022-12-28 15:23:10
 */
// eslint-disable-next-line
var a = 10
import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store/vuex'

// 创建axios实例
const service: AxiosInstance = axios.create({
	baseURL: '',
	timeout: 5000,
	// withCredentials: true
})

// 错误处理
const err = (error: any) => {
	if (error.message.includes('timeout')) {
		ElMessage({
			message: '请求超时，请刷新网页重试',
			type: 'error',
		})
	}
	if (error.response) {
		// const { data } = error.response;
		if (error.response.status === 403) {
			ElMessage({
				message: 'Forbidden',
				type: 'error',
			})
		}
		if (error.response.status === 401) {
			ElMessage({
				message: 'Unauthorized',
				type: 'error',
			})
		}
	}
	return Promise.reject(error)
}

// 请求拦截器
service.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		if (store.getters.getToken) {
			config.headers['x-csrf-token'] = 123
		}
		return config
	},
	err
	// (error) => {
	//     console.log(error);
	//     return Promise.reject(error);
	// }
)

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		const res = response.data
		if (res.code !== 200) {
			return Promise.reject(res)
		}
		return response
	},
	err
	// (error) => {
	//     return Promise.reject(error);
	// }
)

export default service
